package com.cy.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cy.commons.utils.PageUtil;
import com.cy.system.annotation.SysLog;
import com.cy.system.config.UserSession;
import com.cy.system.entity.Account;
import com.cy.system.entity.Dept;
import com.cy.system.entity.Menu;
import com.cy.system.entity.Role;
import com.cy.system.entity.User;
import com.cy.system.entity.UserRole;
import com.cy.system.service.AccountService;
import com.cy.system.service.DeptService;
import com.cy.system.service.MenuService;
import com.cy.system.service.RoleService;
import com.cy.system.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;

@Controller
public class SystemController {
	private final static Logger logger = Logger.getLogger(SystemController.class);
	private static int count = 0;
	
	@Resource
	AccountService accountService;
	@Resource
	UserService userService;
	@Resource
	DeptService deptService;
	@Resource
	MenuService menuService;
	@Resource
	RoleService roleService;

	@RequestMapping("/main")
	public String systemMain(HttpSession session,Model model) {
		User user = (User) session.getAttribute("userSession");
		model.addAttribute("user",user);
		model.addAttribute("menuList",accountService.initMenu(user));
		return "system/main";
	}
	
	@RequestMapping("/performance")
	public String performance(HttpSession session,Model model) {
		User user = (User) session.getAttribute("userSession");
		Account account = accountService.getAccountById(user.getAccountId());
		model.addAttribute("account",account);
		return "system/performance/btnList";
	}
	
	@RequestMapping("/system/index")
	public String systemIndex() {
		return "system/index";
	}
	
	@RequestMapping("/nav")
	public String systemNav(@RequestParam("modelId") Integer modelId,HttpSession session,Model model) {
		UserSession userSession = new UserSession();
		userSession.setUserSession(session);
		User user = (User) session.getAttribute("userSession");
		List<Menu> menuList = accountService.initMenu(user);
		model.addAttribute("modelId",modelId);
		model.addAttribute("menuList",menuList);
		return "system/nav";
	}
	
	@GetMapping("/login")
	public String systemLogin() {
		return "system/login";
	}
	
	@GetMapping("/refuse")
	public String refuse() {
		return "system/refuse";
	}
	
	/*@GetMapping("/logout")
	public String logout() {
		logger.info("==> 退出登录！");
		return "system/login";
	}*/
	
	@RequestMapping("/register")
	public String register() {
		return "system/register";
	}
	
	@PostMapping("/register")
	@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED)
	public String registerPost(Account account,HttpSession session,Model model) {
		logger.info("==> 注册账号"+account);
		
		int resInt = accountService.addAccount(account,session);
		count+=1;
		if(resInt == 1 ) {
			model.addAttribute("msg", "注册成功，请登录！");
		}else {
			model.addAttribute("msg", "注册失败，请重试！");
		}
		return "system/login";
	}
	
	@PostMapping("/addAccountTest")
	@ResponseBody
	@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED)
	public Map<String,Object> addAccountTest(Account account,int countFlag,HttpSession session) {
		logger.info("==> 注册账号"+account);
		int resInt = 0;
		for(int i=0;i<100;i++) {
			/*String loginName= account.getLoginName()+String.valueOf(i);
			account.setLoginName(loginName);*/
			accountService.addAccount(account,session);
		};
		
		if(countFlag==1) {
			count = countFlag-1;
		}
		count+=1;
		Map<String,Object> resMap = new HashMap<String,Object>();
		resMap.put("count",count);	
		logger.info("==> 执行次数["+count+"]");
		return resMap;
	}
	
	@RequestMapping("/delAccount")
	@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED)
	public String delAccount(int accountId,Model model) {
		logger.info("==> 删除账号 accountId["+accountId+"]");
		int resInt = accountService.deleteAccount(accountId);
		resInt = userService.delUserByAccountId(accountId);
		if(resInt == 1) {
			model.addAttribute("msg","删除成功！");
		}else {
			model.addAttribute("msg","删除失败！");
		}
		return "system/account/accountList";
	}
	
	@PostMapping("/login")
	public String toLogin(HttpServletRequest request,Model model) {
		/*Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token =new UsernamePasswordToken(account.getLoginName(),account.getPassword());
		token.setRememberMe(true);
		String exception = "";
		try {
		subject.login(token);
		}catch(Exception e){
			exception = e.getClass().getName();
		}*/
		String exception = (String) request.getAttribute("shiroLoginFailure");
		logger.info("==> 认证失败，进入Controller，异常名称：["+exception+"]");
		String msg = "";
		if (exception != null) {
			if (UnknownAccountException.class.getName().equals(exception)) {
				msg = "您输入的帐号不存在！";
			} else if (IncorrectCredentialsException.class.getName().equals(exception)) {
				msg = "您输入的密码不正确！";
			} else if (LockedAccountException.class.getName().equals(exception)) {
				msg = "您的帐号已被锁定！";
			} else if (ExpiredCredentialsException.class.getName().equals(exception)) {
				msg = "您的帐号已过期！";
			} else if (DisabledAccountException.class.getName().equals(exception)) {
				msg = "您的帐号已被禁用！";
			}
			else if (AuthenticationException.class.getName().equals(exception)) {
				msg = "登录认证失败，请联系管理员检查数据库是否连接正常！";
			}
			else if (ExcessiveAttemptsException.class.getName().equals(exception)) {
				msg = "连续5次登录失败，帐号已被锁定，请与系统管理员联系！";
			}
			else {
				msg = "登录异常！";
			}
		}
		logger.info("==> 认证失败，进入Controller，返回登录页msg：["+msg+"]");
		model.addAttribute("msg",msg);
		return "system/login";
	}
	/*public String toLogin(Account account,HttpSession session,Model model) {
		User user = accountService.toLogin(account,session);		
		if(null!=user) {
			session.setAttribute("userSession", user);
			model.addAttribute("user", session.getAttribute("userSession"));
			List<Menu> menuList = accountService.initMenu(user);
			model.addAttribute("menuList",menuList);
			return "system/main";
		}
		return "system/login";	
	}*/
	@RequestMapping("/userList")
	@RequiresRoles({"部门经理"})
	public String userList() {
		return "system/user/userList";
	}
	@RequestMapping("/userListRe")
	@ResponseBody
	@RequiresRoles({"部门经理"})
	public Map<String,Object> userListRe(int pageNum,int pageSize) {	
		logger.info("==> userList分页，pageNo["+pageNum+"] pageSize["+pageSize+"]");
		Page page = new Page();
		page.setPageNum(pageNum);
		page.setPageSize(pageSize);
		List<Map> resList = userService.getAllUserMap(page);
		PageInfo<Map> pageInfo = new PageInfo<Map>(resList);
		String pageStr = PageUtil.pageStr(pageInfo, "listMgr.getList");
		logger.info("==> pageStr["+pageStr.length()+"]");
		Map<String,Object> resMap = new HashMap<String,Object>();
		resMap.put("resList", resList);
		resMap.put("pageStr", pageStr);
 		return resMap;
	}
	
	@RequestMapping("/accountList")
	@RequiresRoles({"部门经理"})
	public String accountList() {	
		return "system/account/accountList";
	}
	
	@RequestMapping("/accountListRe")
	@ResponseBody
	@RequiresRoles({"部门经理"})
	public Map<String,Object> accountListRe(int pageNum,int pageSize) {	
		logger.info("==> 分页，pageNo["+pageNum+"] pageSize["+pageSize+"]");
		Page page = new Page();
		page.setPageNum(pageNum);
		page.setPageSize(pageSize);
		List<Account> resList = accountService.getAllAccountList(page);
		PageInfo<Account> pageInfo = new PageInfo<Account>(resList);
		String pageStr = PageUtil.pageStr(pageInfo, "listMgr.getList");
		logger.info("==> pageStr["+pageStr.length()+"]");
		Map<String,Object> resMap = new HashMap<String,Object>();
		resMap.put("resList", resList);
		resMap.put("pageStr", pageStr);
 		return resMap;
	}
	
	@RequestMapping("/deptList")
	@RequiresRoles({"部门经理"})
	public String deptList(Model model) {
		model.addAttribute("deptList",deptService.getAllDept());
		return "system/dept/deptList";
	}
	
	
	@RequestMapping("/menuList")
	@RequiresRoles({"部门经理"})
	@SysLog(operType="转发菜单列表页")
	public String menuList(Model model) {
		model.addAttribute("menuList",menuService.getAllMenu());
		
		return "system/menu/menuList";
	}
	
	@RequestMapping("/roleList")
	@RequiresRoles({"部门经理"})
	@SysLog(operType="转发>>角色列表页")
	public String roleList() {
		return "system/role/roleList";
	}
	@RequestMapping("/roleListRe")
	@ResponseBody
	@RequiresRoles({"部门经理"})
	@SysLog(operType="返回>>角色列表")
	public HashMap<String,Object> roleListRe(int pageNum,int pageSize) {
		logger.info("==> roleListRe page["+pageNum+","+pageSize+"]");
		List<Role> resList = roleService.getAllRole(pageNum,pageSize);
		PageInfo<Role> pageInfo = new PageInfo<Role>(resList);
		String pageStr = PageUtil.pageStr(pageInfo, "listMgr.getList");
		
		HashMap<String,Object> resMap = new HashMap<String,Object>();
		resMap.put("pageStr", pageStr);
		resMap.put("resList",resList);
 		return resMap;
	}
	
}
